﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Tb.App.API.Applications.Command.Slaughter;
using Tb.App.Domain.Rabbit.Slaughter;
using Tb.App.ErrorCode;
using Tb.App.Infrastructure.Interfaces;

namespace Tb.App.API.Applications.CommandHandler.Slaughter
{
    /// <summary>
    /// 添加屠宰 企业信息-命令
    /// </summary>
    public class AddSlaughterCommpanyCommandHandler : IRequestHandler<AddSlaughterCommpanyCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<SlaughterCommpany> slaughterCommpanyRep;
        private readonly IMapper mapper;
        private readonly ILogger<AddSlaughterCommpanyCommandHandler> logger;

        public AddSlaughterCommpanyCommandHandler(IBaseRepository<SlaughterCommpany> slaughterCommpanyRep,IMapper mapper,ILogger<AddSlaughterCommpanyCommandHandler> logger)
        {
            this.slaughterCommpanyRep = slaughterCommpanyRep;
            this.mapper = mapper;
            this.logger = logger;
        }
        public async Task<ApiResult<int>> Handle(AddSlaughterCommpanyCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result=new ApiResult<int>();
            //// 获取数据库的执行策略
            var executionStrategy = slaughterCommpanyRep.DB.Database.CreateExecutionStrategy();
            // 使用执行策略执行事务操作
            await executionStrategy.ExecuteAsync(async () =>
            {
                using (var tran = await slaughterCommpanyRep.DB.Database.BeginTransactionAsync(cancellationToken))
                {
                    try
                    {
                        var list= slaughterCommpanyRep.GetAll().Where(x => x.Batch == request.Batch && !x.IsDel).ToList();
                        list.ForEach(o =>
                        {
                            o.IsDel = true;
                        });
                        await slaughterCommpanyRep.UpdateRange(list);


                        var entity = mapper.Map<SlaughterCommpany>(request);
                        var a = await slaughterCommpanyRep.AddAsync(entity);
                        if (a > 0)
                        {
                            result.Code = ApiEnum.添加成功;
                            result.Message = ApiEnum.添加成功.ToString();
                            result.Data = a;
                        }
                        else
                        {
                            result.Code = ApiEnum.添加失败;
                            result.Message = ApiEnum.添加失败.ToString();
                            result.Data = a;
                        }
                        await tran.CommitAsync(cancellationToken);
                    }
                    catch (Exception ex)
                    {
                        await tran.RollbackAsync(cancellationToken);
                        logger.LogError(ex, "添加屠宰企业信息异常");
                        result.Code = ApiEnum.添加失败;
                        result.Message = ex.Message;
                        result.Data = 0;
                    }
                }
            });
            return result;

        }
    }
}
